<?php

namespace app\admin\controller;

use app\admin\model\TeacherSubscribe;
use app\admin\model\User;
use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 教师身份管理
 *
 * @icon fa fa-circle-o
 */
class TeacherDetail extends Backend
{

    /**
     * TeacherDetail模型对象
     * @var \app\admin\model\TeacherDetail
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\TeacherDetail;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $param = $this->request->param();
        $dtl_where = ' 1=1';
        if(isset($param['info_id'])&&$param['info_id']){
            $dtl_where .= ' and info_id = '.$param['info_id'];
        }

        $list = $this->model->with([
            'club' => function ($query) {
                $query->withField('name');
            },'clubDtl' => function ($query) {
                $query->withField('name');
            }]);
        $list = $list->where($where)->where($dtl_where)
            ->order($sort, $order)
            ->paginate($limit);

        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    public function add()
    {
        if (false === $this->request->isPost()) {
            // 获取学历选项数据
            $educationList = \app\admin\model\IdentityInfo::xl();
            $this->view->assign('educationList', $educationList);
            // 从URL参数中获取info_id并传递给视图
            $info_id = $this->request->get('info_id', '');
            $this->view->assign('info_id', $info_id);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        $find = \app\admin\model\TeacherDetail::where(['info_id'=>$params['info_id'],'club_two_id'=>$params['club_two_id'],'is_premium'=>$params['is_premium']])->find();
        if($find){
            $this->error('当前教师已存在相同的社团和精品设置');
        }
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }

//            $week = explode(',',$params['appointment_time_week']);
//            $sub = TeacherSubscribe::up_subscribe($week,$params['user_id']);
//            if($sub['code'] == 0){
//                $this->error($sub['msg']);
//            }
            // 检查TeacherDetail表中的必要字段
            $detailComplete = $params['club_one_id']&&$params['club_two_id']&&$params['teacher_certification'] &&$params['diploma']&&$params['occupational_qualifications']&&$params['professional_skill'];
            
            // 检查关联的IdentityInfo表中的三个字段
            $identityInfo = \app\admin\model\IdentityInfo::where(['id'=>$params['info_id']])->find();
            $identityComplete = false;
            if($identityInfo){
                $identityComplete = !empty($identityInfo['health_certificate']) && !empty($identityInfo['identity_card_img']) && !empty($identityInfo['no_crime']);
            }
            
            if($detailComplete && $identityComplete){
                $params['is_all'] = '是';
            }else{
                $params['is_all'] = '否';
            }
            // 设置默认显示状态
            if (!isset($params['detail_status']) || empty($params['detail_status'])) {
                $params['detail_status'] = 1;
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
            if($params['hourly_rate']){
                $td_h = \app\admin\model\TeacherDetail::where(['info_id'=>$params['info_id']])->where("hourly_rate>0")->order('hourly_rate','asc')->find();
                if($td_h){
                    if($td_h['hourly_rate']>$params['hourly_rate']){
                        \app\admin\model\IdentityInfo::where(['id'=>$params['info_id']])->update(['lowest_hourly_rate'=>$params['hourly_rate']]);
                    }
                }
            }
            if($params['people']){
                $td_all = \app\admin\model\TeacherDetail::where(['info_id'=>$params['info_id'],'detail_status'=>1])->select();
                $score = 0;
                foreach ($td_all as $k=>$v){
                    $score = precisionRestore($score,$v['people'],'加法');
                }
                \app\admin\model\IdentityInfo::where(['id'=>$params['info_id']])->update(['people'=>$score]);
            }
            if($params['order_num']){
                $td_all = \app\admin\model\TeacherDetail::where(['info_id'=>$params['info_id'],'detail_status'=>1])->select();
                $order_num = 0;
                foreach ($td_all as $k=>$v){
                    $order_num = precisionRestore($order_num,$v['order_num'],'加法');
                }
                \app\admin\model\IdentityInfo::where(['id'=>$params['info_id']])->update(['order_num_all'=>$order_num]);
            }
            if ($result) {
                // 获取自增主键的值
                $insertId = $this->model->id; // 假设主键字段为'id'
                // 复用之前查询的identityInfo
                if ($identityInfo && $identityInfo['identity_type'] == '教师') {
                    // 使用队列异步生成Word文档
                    \think\Queue::push('app\\job\\GenerateTeacherWordJob', ['user_id' => $identityInfo['user_id'],'detail_id'=>$insertId], 'default');
                }
                // 或者如果主键字段为'uid'，则使用 $this->model->uid
            }
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }

        $this->success();
    }

    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            // 获取学历选项数据
            $educationList = \app\admin\model\IdentityInfo::xl();
            $this->view->assign('educationList', $educationList);
            // 如果URL参数中有info_id，优先使用URL参数，否则使用记录中的info_id
            $info_id = $this->request->get('info_id', $row['info_id'] ?? '');
            $this->view->assign('row', $row);
            $this->view->assign('info_id', $info_id);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;

        $find = \app\admin\model\TeacherDetail::where(['info_id'=>$params['info_id'],'club_two_id'=>$params['club_two_id'],'is_premium'=>$params['is_premium']])->where("id != {$ids}")->find();
        if($find){
            $this->error('当前教师已存在相同的社团和精品设置');
        }

        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }


            // 检查TeacherDetail表中的必要字段
            $detailComplete = $params['club_one_id']&&$params['club_two_id']&&$params['teacher_certification'] &&$params['diploma']&&$params['occupational_qualifications']&&$params['professional_skill'];
            
            // 检查关联的IdentityInfo表中的三个字段
            $info_id = isset($params['info_id']) ? $params['info_id'] : $row['info_id'];
            $identityInfo = \app\admin\model\IdentityInfo::where(['id'=>$info_id])->find();
            $identityComplete = false;
            if($identityInfo){
                $identityComplete = !empty($identityInfo['health_certificate']) && !empty($identityInfo['identity_card_img']) && !empty($identityInfo['no_crime']);
            }
            
            if($detailComplete && $identityComplete){
                $params['is_all'] = '是';
            }else{
                $params['is_all'] = '否';
            }
            $result = $row->allowField(true)->save($params);

            // 复用之前查询的identityInfo
            // 提交事务后，添加队列任务生成Word文档
            if ($result !== false && $identityInfo && $identityInfo['identity_type'] == '教师') {
                // 使用队列异步生成Word文档
                \think\Queue::push('app\\job\\GenerateTeacherWordJob', ['user_id' => $identityInfo['user_id'],'detail_id'=>$row['id']], 'default');
            }

            Db::commit();
            if($row['club_two_id'] != $params['club_two_id']){
                // 复用之前查询的identityInfo
                if($identityInfo){
                    \app\admin\model\Sharpshooter::where(['user_id'=>$identityInfo['user_id'],'club_two_id'=>$row['club_two_id']])->update(['club_two_id'=>$params['club_two_id']]);
                }
            }
            if($params['hourly_rate']){
                $td_h = \app\admin\model\TeacherDetail::where(['info_id'=>$params['info_id']])->where("hourly_rate>0")->order('hourly_rate','asc')->find();
                if($td_h){
                    if($td_h['hourly_rate']>$params['hourly_rate']){
                        \app\admin\model\IdentityInfo::where(['id'=>$params['info_id']])->update(['lowest_hourly_rate'=>$params['hourly_rate']]);
                    }
                }
            }
            if($params['people']){
                $td_all = \app\admin\model\TeacherDetail::where(['info_id'=>$params['info_id'],'detail_status'=>1])->select();
                $score = 0;
                foreach ($td_all as $k=>$v){
                    $score = precisionRestore($score,$v['people'],'加法');
                }
                \app\admin\model\IdentityInfo::where(['id'=>$params['info_id']])->update(['people'=>$score]);
            }
            if($params['order_num']){
                $td_all = \app\admin\model\TeacherDetail::where(['info_id'=>$params['info_id'],'detail_status'=>1])->select();
                $order_num = 0;
                foreach ($td_all as $k=>$v){
                    $order_num = precisionRestore($order_num,$v['order_num'],'加法');
                }
                \app\admin\model\IdentityInfo::where(['id'=>$params['info_id']])->update(['order_num_all'=>$order_num]);
            }
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    /**
     * 批量更新
     *
     * @param $ids
     * @return void
     */
    public function multi($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $ids = $ids ?: $this->request->post('ids');
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }

        if (false === $this->request->has('params')) {
            $this->error(__('No rows were updated'));
        }
        parse_str($this->request->post('params'), $values);
        $values = $this->auth->isSuperAdmin() ? $values : array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
        if (empty($values)) {
            $this->error(__('You have no permission'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $count = 0;
        $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
        foreach ($list as $item) {
            // 计算批量更新后该条记录的 info_id、club_two_id、is_premium
            $newInfoId      = $item['info_id'];
            $newClubTwoId   = $item['club_two_id'];
            $newIsPremium   = array_key_exists('is_premium', $values) ? $values['is_premium'] : $item['is_premium'];

            $exists = \app\admin\model\TeacherDetail::where([
                'info_id'     => $newInfoId,
                'club_two_id' => $newClubTwoId,
                'is_premium'  => $newIsPremium,
            ])
                ->where('id', '<>', $item['id'])
                ->find();
            if ($exists) {
                $this->error('更新失败：存在教师已配置相同的社团和精品设置');
            }

        }
        Db::startTrans();
        try {
            $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
            foreach ($list as $item) {
                $count += $item->allowField(true)->isUpdate(true)->save($values);
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were updated'));
    }

}
